package org.hxyjs.dao.impl;

import org.hxyjs.dao.FieldDao;
import org.hxyjs.entity.Field;
import org.hxyjs.mapper.FieldMapper;
import org.hxyjs.page.PageInfo;
import org.hxyjs.utils.GenNumTools;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Repository("fieldDao")//一般实现类不会直接生成默认对象名 而是使用 接口的默认对象名

public class FieldDaoImpl implements FieldDao {
    @Resource //autowired 会装配能够直接扫描到的对象  resource spring容器运行的时候才找到需要的对象  注入
    private FieldMapper fieldMapper;

    //查询全部
    public List<Field> getAllFields() throws Exception {
        return fieldMapper.selectByExample(null);
    }

    //按主键查询
    @Override
    public Field getFieldByFno(String fno) throws Exception {
        return fieldMapper.selectByPrimaryKey(fno);
    }

    //分页查询
    @Override
    public List<Field> getFieldByPage(PageInfo pageInfo) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("currPage", pageInfo.getCurrPage());
        map.put("pageSize", pageInfo.getPageSize());
        int itemCount = (int) fieldMapper.countByExample(null);
        pageInfo.setItemCount(itemCount);
        return fieldMapper.getFieldByPage(map);
    }


    //删除
    @Override
    public Integer deleteFieldByFno(String fno) {
        return fieldMapper.deleteByPrimaryKey(fno);
    }

    //修改
    @Override
    public Integer updateFieldByFno(Field field) {
        return fieldMapper.updateByPrimaryKey(field);
}


    //增加
    @Override
    public Integer addField(Field field) {
        field.setFno(initId());
        System.out.println(field.getFno());
        return fieldMapper.insertSelective(field);
    }

    public String initId() {
        String maxFno = fieldMapper.getMaxFno();
        maxFno = Optional.ofNullable(maxFno).orElse("0000");
        return GenNumTools.initId("f", 4, maxFno);
    }


}